package calculator.math;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * Created by liyf on 2015/3/30 0030.
 * 计算从 s到e的总和
 */
public class Count extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 2;
    private int start;
    private int end;

    public Count(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //如果任务大于阈值，就分裂成两个子任务计算
            int middle = (start + end) / 2;
            Count leftTask = new Count(start, middle);
            Count rightTask = new Count(middle + 1, end);
            //执行子任务
            leftTask.fork();
            rightTask.fork();
            //等待子任务执行完，并得到其结果

            int leftResult = leftTask.join();
            int rightResult = rightTask.join();
            //合并子任务
            sum = leftResult + rightResult;
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //生成一个计算任务，负责计算1+2+3+4
        Count task = new Count(1, 100);
        //执行一个任务
//		Future<Integer> resultFuture = forkJoinPool.submit(task);
//		try{
//			System.out.println(resultFuture.get());
//		}catch(InterruptedException e){
//		}catch(ExecutionException e){
//		}
        forkJoinPool.invoke(task);
        System.out.println(task.getRawResult());
    }

}
